﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Catering_Rules;
using Catering_DBOpertion;

namespace Catering.Catering_Page.Caipin.Caipin_jcsz
{
    public partial class YuanliaoInfo : System.Web.UI.Page
    {
        View_Operaction_Common voc = new View_Operaction_Common();
        T_Dish tDish = new T_Dish();//菜品管理
        T_DishInfo tDishInfo = new T_DishInfo();//菜品详细管理

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ImageButton1.Visible = (Request.QueryString["cid"] == null);
                this.ImageButton2.Visible = (Request.QueryString["cid"] != null);

                voc.DropDownListDataBind_RawMaterials(DDLzhongsu);
                if (DDLzhongsu.Items.Count > 0)
                {
                    voc.DropDownListDataBind_RawMaterialsInfo(DDLzhongsumin, DDLzhongsu.Items[0].Value);
                }
                this.LoadData();

                if (Request.QueryString["cid"] != null)
                {
                    this.Show_Raw(Request.QueryString["cid"].ToString());
                }
            }
        }

        //加载页面数据
        public void LoadData()
        {
            DataTable dt_Unit = new Catering_Rules.Units().GetAllList().Tables[0];
            this.Drop_U1.LoadDrop(dt_Unit, "id", "UName");
            this.Drop_U2.LoadDrop(dt_Unit, "id", "UName");
            this.Drop_U3.LoadDrop(dt_Unit, "id", "UName");
            this.Drop_U4.LoadDrop(dt_Unit, "id", "UName");
            this.Drop_Units.LoadDrop(dt_Unit, "id", "UName");

            DataTable dt_Area = new Catering_Rules.Area().GetAllList().Tables[0];
            this.Drop_Area.LoadDrop(dt_Area, "id", "Name");

            DataTable dt_StorageRoom = new Catering_Rules.StorageRoom().GetAllList().Tables[0];
            this.Drop_kufang.LoadDrop(dt_StorageRoom, "id", "RoomID");

            DataTable dt_zs = new Catering_Rules.RawMaterialsType().GetAllList().Tables[0];
            this.Drop_zs.LoadDrop(dt_zs, "id", "Name");

        }

        //清理食物界面
        protected void ButClear_Raw_Click(object sender, EventArgs e)
        {
            this.ImageButton1.Visible = true;
            this.ImageButton2.Visible = false;

            this.txtShiWumc.Text = "";
            this.txtGongYong.Text = "";

            foreach (Control c in this.Pan_EN.Controls)
            {
                TextBox tb = c as TextBox;
                if (tb != null)
                {
                    tb.Text = string.Empty;
                }
            }
            this.txtzhesun.Text = string.Empty;
            this.txt_KeShi.Text = string.Empty;

            this.txt_U1.Text = string.Empty;
            this.txt_U2.Text = string.Empty;
            this.txt_U3.Text = string.Empty;
            this.txt_U4.Text = string.Empty;
            this.txt_pinghao.Text = string.Empty;
            this.txt_shibu.Text = string.Empty;
            this.txt_shuifen.Text = string.Empty;
            this.txt_SafetyTips.Text = string.Empty;
            this.LoadData();
        }

        //修改原料
        protected void But_Raw_Click_Edit(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(Request.QueryString["cid"].ToString());

            #region 原料添加验证

            string YRawName = this.txtShiWumc.Text;
            string YUnit = this.Drop_Units.Items[0].Text;
            try
            {
                YUnit = this.Drop_Units.SelectedItem.Text;
            }
            catch { }

            if (string.IsNullOrEmpty(YRawName))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('原料名称不能为空，保存失败！')</script>");
                return;
            }

            Dictionary<string, decimal> list = new Dictionary<string, decimal>();
            if (!string.IsNullOrEmpty(this.txt_U1.Text))
            {
                decimal u1num = 1;
                decimal.TryParse(this.txt_U1.Text, out u1num);
                if (u1num != 1)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                    return;
                }
                string YValue = this.Drop_U1.Items[0].Value;
                YValue = this.Drop_U1.SelectedItem.Value;
                list.Add(YValue, 1);
                if (!string.IsNullOrEmpty(this.txt_U2.Text))
                {
                    u1num = 0;
                    decimal.TryParse(this.txt_U2.Text, out u1num);
                    if (u1num <= 0)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    YValue = this.Drop_U2.Items[0].Value;
                    YValue = this.Drop_U2.SelectedItem.Value;
                    try
                    {
                        list.Add(YValue, u1num);
                    }
                    catch
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    if (!string.IsNullOrEmpty(this.txt_U3.Text))
                    {
                        u1num = 0;
                        decimal.TryParse(this.txt_U3.Text, out u1num);
                        if (u1num <= 0)
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        YValue = this.Drop_U3.Items[0].Value;
                        YValue = this.Drop_U3.SelectedItem.Value;
                        try
                        {
                            list.Add(YValue, u1num);
                        }
                        catch
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        if (!string.IsNullOrEmpty(this.txt_U4.Text))
                        {
                            u1num = 0;
                            decimal.TryParse(this.txt_U4.Text, out u1num);
                            if (u1num <= 0)
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                            YValue = this.Drop_U4.Items[0].Value;
                            YValue = this.Drop_U4.SelectedItem.Value;
                            try
                            {
                                list.Add(YValue, u1num);
                            }
                            catch
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                        }
                    }
                }
            }

            if (list.Count == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格不能为空，保存失败！')</script>");
                return;
            }
            else if (!list.ContainsKey(this.Drop_Units.SelectedItem.Value))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('单位必须包含在规格内，保存失败！')</script>");
                return;
            }

            #endregion

            #region 验证此地区的相应品号原料是否已入库，如已入库，并且品号为空即删除此品号，则保存失败

            if (string.IsNullOrEmpty(this.txt_pinghao.Text))
            {
                //该原料在此地区的品号
                DataTable ra = new Catering_Rules.RawMaterial_Area().GetList(" RAWID= " + id + " AND AreaID=" + this.Drop_Area.SelectedValue + " ").Tables[0];

                if (ra != null && ra.Rows.Count > 0)
                {
                    string dbid = ra.Rows[0]["InDBid"].ToString();
                    int raid = Convert.ToInt32(ra.Rows[0]["id"]);
                    DataTable dt_IndbInfo = new Catering_Rules.InDbInfo().GetList(" RAWID= " + id + " AND InDBid='" + dbid + "' ").Tables[0];
                    if (dt_IndbInfo.Rows.Count > 0)
                    {
                        dt_IndbInfo.Dispose();
                        //判断是否存在相同品号的其他原料,并判断是否入库，如未入库删除
                        DataTable ra1 = new Catering_Rules.RawMaterial_Area().GetList("id<>" + raid + " AND InDBid= '" + dbid + "' AND AreaID=" + this.Drop_Area.SelectedValue + " ").Tables[0];
                        if (ra1 != null && ra1.Rows.Count > 0)
                        {
                            for (int i = 0; i < ra1.Rows.Count; i++)
                            {
                                int rawid1 = Convert.ToInt32(ra1.Rows[i]["RAWID"]);
                                int raid1 = Convert.ToInt32(ra1.Rows[i]["id"]);

                                if (rawid1 > 0)
                                {
                                    if (new Catering_Rules.InDbInfo().GetList(" RAWID= " + rawid1 + " AND InDBid='" + dbid + "' ").Tables[0].Rows.Count <= 0)
                                    {
                                        new Catering_Rules.RawMaterial_Area().Delete(raid1);
                                    }
                                }
                            }
                            ra1.Dispose();
                        }

                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('此品号的原料已入库，保存失败！')</script>");
                        return;
                    }
                    else
                    {
                        new Catering_Rules.RawMaterial_Area().Delete(raid);
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！')</script>");
                        return;
                    }
                }
                ra.Dispose();
            }
            else
            {
                bool issave = true;
                //判断此地区是否存在其他原料的此品号
                DataTable dt_pinhao0 = new Catering_Rules.RawMaterial_Area().GetList("RawID<>" + id + " AND InDBid='" + this.txt_pinghao.Text.Trim() + "' and AreaID=" + this.Drop_Area.SelectedValue).Tables[0];
                if (dt_pinhao0 != null && dt_pinhao0.Rows.Count > 0)
                {
                    for (int j = 0; j < dt_pinhao0.Rows.Count; j++)
                    {
                        int raid0 = Convert.ToInt32(dt_pinhao0.Rows[j]["id"]);
                        int rawid0 = Convert.ToInt32(dt_pinhao0.Rows[j]["RawID"]);
                        if (new Catering_Rules.InDbInfo().GetList(" RAWID= " + rawid0 + " AND InDBid='" + this.txt_pinghao.Text.Trim() + "' ").Tables[0].Rows.Count <= 0)
                        {
                            new Catering_Rules.RawMaterial_Area().Delete(raid0);
                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('已存在此品号的原料，并已经入库，保存失败！')</script>");
                            issave = false;
                        }
                    }
                    dt_pinhao0.Dispose();
                }
                if (!issave) return;
            }

            #endregion

            this.UpdateRawToDatabase(id);
            this.UpdateElementToDatabase(id);
            new Catering_Rules.RawMaterial_Unit().DeleteListBywhere("RawMaterialID=" + id);
            this.AddUnit(id);
            this.UpdateDishAreaIDS(id);//同步对应的菜品区域
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！');window.parent.SetRAWName('" + id + "','" + txtShiWumc.Text.Trim() + "');</script>");
        }

        //添加原料
        protected void But_Raw_Click_Add(object sender, EventArgs e)
        {
            #region 原料添加验证

            string YRawName = this.txtShiWumc.Text;
            string YUnit = this.Drop_Units.Items[0].Text;
            try
            {
                YUnit = this.Drop_Units.SelectedItem.Text;
            }
            catch { }

            if (string.IsNullOrEmpty(YRawName))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('原料名称不能为空，保存失败！')</script>");
                return;
            }

            Dictionary<string, decimal> list = new Dictionary<string, decimal>();
            if (!string.IsNullOrEmpty(this.txt_U1.Text))
            {
                decimal u1num = 1;
                decimal.TryParse(this.txt_U1.Text, out u1num);
                if (u1num != 1)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                    return;
                }
                string YValue = this.Drop_U1.Items[0].Value;
                YValue = this.Drop_U1.SelectedItem.Value;
                list.Add(YValue, 1);
                if (!string.IsNullOrEmpty(this.txt_U2.Text))
                {
                    u1num = 0;
                    decimal.TryParse(this.txt_U2.Text, out u1num);
                    if (u1num <= 0)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    YValue = this.Drop_U2.Items[0].Value;
                    YValue = this.Drop_U2.SelectedItem.Value;
                    try
                    {
                        list.Add(YValue, u1num);
                    }
                    catch
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    if (!string.IsNullOrEmpty(this.txt_U3.Text))
                    {
                        u1num = 0;
                        decimal.TryParse(this.txt_U3.Text, out u1num);
                        if (u1num <= 0)
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        YValue = this.Drop_U3.Items[0].Value;
                        YValue = this.Drop_U3.SelectedItem.Value;
                        try
                        {
                            list.Add(YValue, u1num);
                        }
                        catch
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        if (!string.IsNullOrEmpty(this.txt_U4.Text))
                        {
                            u1num = 0;
                            decimal.TryParse(this.txt_U4.Text, out u1num);
                            if (u1num <= 0)
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                            YValue = this.Drop_U4.Items[0].Value;
                            YValue = this.Drop_U4.SelectedItem.Value;
                            try
                            {
                                list.Add(YValue, u1num);
                            }
                            catch
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                        }
                    }
                }
            }

            if (list.Count == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格不能为空，保存失败！')</script>");
                return;
            }
            else if (!list.ContainsKey(this.Drop_Units.SelectedItem.Value))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('单位必须包含在规格内，保存失败！')</script>");
                return;
            }

            #endregion

            //判断此地区是否存在其他原料的此品号
            bool issave = true;
            DataTable dt_pinhao0 = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + this.txt_pinghao.Text.Trim() + "' and AreaID=" + this.Drop_Area.SelectedValue).Tables[0];
            if (dt_pinhao0 != null && dt_pinhao0.Rows.Count > 0)
            {
                for (int j = 0; j < dt_pinhao0.Rows.Count; j++)
                {
                    int raid0 = Convert.ToInt32(dt_pinhao0.Rows[j]["id"]);
                    int rawid0 = Convert.ToInt32(dt_pinhao0.Rows[j]["RawID"]);
                    if (new Catering_Rules.InDbInfo().GetList(" RAWID= " + rawid0 + " AND InDBid='" + this.txt_pinghao.Text.Trim() + "' ").Tables[0].Rows.Count <= 0)
                    {
                        new Catering_Rules.RawMaterial_Area().Delete(raid0);
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('已存在此品号的原料，并已经入库，保存失败！')</script>");
                        dt_pinhao0.Dispose();
                        issave = false;
                    }
                }
                dt_pinhao0.Dispose();
            }
            if (!issave) return;
            int iID = AddRawToDatabase();
            this.SetElementToDatabase(iID);
            this.AddUnit(iID);

            DataTable dt = new RawMaterialsInfo().GetList("RMID=" + this.DDLzhongsu.SelectedValue).Tables[0];
            string IsTypeInfo = "";
            string TypeID = "";
            if (dt != null && dt.Rows.Count == 1 && dt.Rows[0]["Name"].ToString() == this.DDLzhongsu.SelectedItem.Text)
            {
                IsTypeInfo = "false";
                TypeID = Convert.ToInt32(this.DDLzhongsu.SelectedValue).ToString();
                dt.Dispose();
            }
            else
            {
                IsTypeInfo = "true";
                TypeID = Convert.ToInt32(this.DDLzhongsumin.SelectedValue).ToString();
            }

            string RawID = iID.ToString();
            string RawName = txtShiWumc.Text.Trim();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功！');window.parent.AddRAWName('" + IsTypeInfo + "', '" + TypeID + "', '" + RawID + "', '" + RawName + "');</script>");
        }

        //同步更新菜品所属区域
        public void UpdateDishAreaIDS(int RawID)
        {
            DataTable DishInfoDt=tDishInfo.GetList("RawID=" + RawID).Tables[0];
            if (DishInfoDt != null && DishInfoDt.Rows.Count > 0)
            {
                for (int i = 0; i < DishInfoDt.Rows.Count; i++)
                {
                    tDish.UpdateAreaIDByDishID(int.Parse(DishInfoDt.Rows[i]["DID"].ToString()));
                }
            }
        }

        //保存原料基本信息
        public int AddRawToDatabase()
        {
            Catering_Model.E_RawMaterial cnrm = new Catering_Model.E_RawMaterial();
            Catering_Rules.T_RawMaterial crrm = new Catering_Rules.T_RawMaterial();
            int i = crrm.GetMaxId();
            decimal usefulpart = 100;
            Decimal.TryParse(this.txt_KeShi.Text, out usefulpart);
            cnrm.id = i;
            cnrm.RAWName = txtShiWumc.Text.Trim();
            cnrm.RAWTID = Convert.ToInt32(this.Drop_kufang.SelectedValue);
            cnrm.RAWID = Convert.ToInt32(this.DDLzhongsu.SelectedValue);//原料大类
            cnrm.RAWIDS = Convert.ToInt32(this.DDLzhongsumin.SelectedValue);//原料细类
            cnrm.RAWSid = "0";
            cnrm.RAWWid = "0";
            cnrm.InDBid = "";//没有用处了。。
            cnrm.RAWZS = Convert.ToInt32(this.Drop_zs.SelectedValue);
            cnrm.temp1 = this.txtzhesun.Text.Trim();
            cnrm.temp2 = this.Drop_Units.SelectedValue;
            cnrm.Back = this.txtGongYong.Text.Trim();
            cnrm.SafetyTips = this.txt_SafetyTips.Text.Trim();
            cnrm.UsefulPart = usefulpart > 100 ? 100 : (usefulpart <= 0 ? 100 : usefulpart);
            crrm.Add(cnrm);

            Catering_Model.RawMaterial_Area md_Raw_Area = new Catering_Model.RawMaterial_Area();
            md_Raw_Area.id = new Catering_Rules.RawMaterial_Area().GetMaxId();
            md_Raw_Area.RawID = i;
            md_Raw_Area.AreaID = Convert.ToInt32(this.Drop_Area.SelectedValue);
            md_Raw_Area.InDBid = this.txt_pinghao.Text;
            new Catering_Rules.RawMaterial_Area().Add(md_Raw_Area);
            return i;
        }

        //保存营养素
        public void SetElementToDatabase(int i)
        {
            foreach (Control c in this.Pan_EN.Controls)
            {
                TextBox tb = c as TextBox;
                if (tb != null)
                {
                    Catering_Model.NutrientComposition md = new Catering_Model.NutrientComposition();
                    md.RawID = i;
                    md.NutritionElementsID = Convert.ToInt32(tb.ID.Replace("txt_", ""));
                    md.Content = tb.Text.Trim() == "" ? "0" : tb.Text.Trim();
                    new Catering_Rules.NutrientComposition().Add(md);
                }
            }
        }

        //保存规格
        public void AddUnit(int ID)
        {
            Dictionary<string, decimal> list = new Dictionary<string, decimal>();
            if (!string.IsNullOrEmpty(this.txt_U1.Text))
            {
                decimal u1num = 1;
                decimal.TryParse(this.txt_U1.Text, out u1num);
                if (u1num != 1)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                    return;
                }
                string YValue = this.Drop_U1.Items[0].Value;
                YValue = this.Drop_U1.SelectedItem.Value;
                list.Add(YValue, 1);
                if (!string.IsNullOrEmpty(this.txt_U2.Text))
                {
                    u1num = 0;
                    decimal.TryParse(this.txt_U2.Text, out u1num);
                    if (u1num <= 0)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    YValue = this.Drop_U2.Items[0].Value;
                    YValue = this.Drop_U2.SelectedItem.Value;
                    try
                    {
                        list.Add(YValue, u1num);
                    }
                    catch
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                        return;
                    }
                    if (!string.IsNullOrEmpty(this.txt_U3.Text))
                    {
                        u1num = 0;
                        decimal.TryParse(this.txt_U3.Text, out u1num);
                        if (u1num <= 0)
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        YValue = this.Drop_U3.Items[0].Value;
                        YValue = this.Drop_U3.SelectedItem.Value;
                        try
                        {
                            list.Add(YValue, u1num);
                        }
                        catch
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                            return;
                        }
                        if (!string.IsNullOrEmpty(this.txt_U4.Text))
                        {
                            u1num = 0;
                            decimal.TryParse(this.txt_U4.Text, out u1num);
                            if (u1num <= 0)
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                            YValue = this.Drop_U4.Items[0].Value;
                            YValue = this.Drop_U4.SelectedItem.Value;
                            try
                            {
                                list.Add(YValue, u1num);
                            }
                            catch
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('规格填写错误，保存失败！')</script>");
                                return;
                            }
                        }
                    }
                }
            }
            foreach (string item in list.Keys)
            {
                Catering_Model.RawMaterial_Unit md = new Catering_Model.RawMaterial_Unit();
                //md.id = new Catering_Rules.RawMaterial_Unit().GetMaxId();
                md.RawMaterialID = ID;
                md.Number = list[item].ToString();
                md.UnitID = Convert.ToInt32(item);
                new Catering_Rules.RawMaterial_Unit().Add(md);
            }
        }

        public void UpdateRawToDatabase(Int32 i)
        {
            Catering_Model.E_RawMaterial cnrm = new Catering_Model.E_RawMaterial();
            Catering_Rules.T_RawMaterial crrm = new Catering_Rules.T_RawMaterial();
            cnrm.id = i;
            cnrm.RAWName = txtShiWumc.Text.Trim();
            cnrm.RAWTID = Convert.ToInt32(this.Drop_kufang.SelectedValue);
            cnrm.RAWID = Convert.ToInt32(this.DDLzhongsu.SelectedValue);
            cnrm.RAWIDS = Convert.ToInt32(this.DDLzhongsumin.SelectedValue);
            cnrm.RAWSid = this.txt_shibu.Text.Trim();
            cnrm.RAWWid = this.txt_shuifen.Text.Trim();
            cnrm.temp2 = this.Drop_Units.SelectedValue;
            cnrm.InDBid = "";


            DataTable dt_pinhao = new Catering_Rules.RawMaterial_Area().GetList("RawID=" + i.ToString() + " and AreaID=" + this.Drop_Area.SelectedValue).Tables[0];
            if (dt_pinhao != null && dt_pinhao.Rows.Count > 0)//此地区存在此原料ID，将要修改品号
            {
                Catering_Model.RawMaterial_Area md_Raw_Area = new Catering_Model.RawMaterial_Area();
                md_Raw_Area.id = Convert.ToInt32(dt_pinhao.Rows[0]["id"].ToString());
                md_Raw_Area.RawID = i;
                md_Raw_Area.AreaID = Convert.ToInt32(this.Drop_Area.SelectedValue);
                md_Raw_Area.InDBid = this.txt_pinghao.Text;
                new Catering_Rules.RawMaterial_Area().Update(md_Raw_Area);
                dt_pinhao.Dispose();
            }
            else //此地区不存在此原料ID，添加
            {
                Catering_Model.RawMaterial_Area md_Raw_Area = new Catering_Model.RawMaterial_Area();
                md_Raw_Area.id = new Catering_Rules.RawMaterial_Area().GetMaxId();
                md_Raw_Area.RawID = i;
                md_Raw_Area.AreaID = Convert.ToInt32(this.Drop_Area.SelectedValue);
                md_Raw_Area.InDBid = this.txt_pinghao.Text;
                new Catering_Rules.RawMaterial_Area().Add(md_Raw_Area);
            }

            cnrm.RAWZS = Convert.ToInt32(this.Drop_zs.SelectedValue);
            cnrm.temp1 = this.txtzhesun.Text.Trim();
            cnrm.Back = this.txtGongYong.Text.Trim();
            cnrm.SafetyTips = this.txt_SafetyTips.Text.Trim();
            decimal usefulpart = 100;
            Decimal.TryParse(this.txt_KeShi.Text.Trim(), out usefulpart);
            cnrm.UsefulPart = usefulpart > 100 ? 100 : (usefulpart <= 0 ? 100 : usefulpart);
            crrm.Update(cnrm);

        }

        //修改营养素
        public void UpdateElementToDatabase(Int32 i)
        {
            new Catering_Rules.NutrientComposition().DeleteListBywhere("RawID=" + i.ToString());
            this.SetElementToDatabase(i);
        }

        protected void DDLzhongsu_SelectedIndexChanged(object sender, EventArgs e)
        {
            voc.DropDownListDataBind_RawMaterialsInfo(DDLzhongsumin, DDLzhongsu.SelectedValue);
        }

        private void Show_Raw(string strRawID)
        {
            Catering_Rules.T_RawMaterial crrm = new Catering_Rules.T_RawMaterial();
            if (strRawID != null && strRawID.Length > 0)
            {
                Catering_Model.E_RawMaterial cmrm = crrm.GetModel(Convert.ToInt32(strRawID));
                if (cmrm != null)
                {
                    txtShiWumc.Text = cmrm.RAWName;
                    int i = cmrm.id;
                    this.DDLzhongsu.SelectedValue = cmrm.RAWID.ToString();
                    voc.DropDownListDataBind_RawMaterialsInfo(DDLzhongsumin, DDLzhongsu.SelectedValue);
                    this.DDLzhongsumin.SelectedValue = cmrm.RAWIDS < 0 ? "1" : cmrm.RAWIDS.ToString();
                    this.txt_shibu.Text = (cmrm.RAWSid == null ? "" : cmrm.RAWSid);
                    this.txt_shuifen.Text = (cmrm.RAWWid == null ? "" : cmrm.RAWWid);
                    this.txtGongYong.Text = cmrm.Back;
                    this.txtzhesun.Text = cmrm.temp1;
                    this.txt_KeShi.Text = cmrm.UsefulPart <= 0 ? "100" : cmrm.UsefulPart.ToString("G");
                    this.txt_SafetyTips.Text = cmrm.SafetyTips;
                    this.LoadUnit(i);
                    this.Drop_Units.SelectedValue = cmrm.temp2;
                    try
                    {
                        this.Drop_kufang.SelectedValue = cmrm.RAWTID.ToString();
                    }
                    catch { }

                    try
                    {
                        this.Drop_zs.SelectedValue = cmrm.RAWZS.ToString();
                    }
                    catch { }


                    DataTable dt_pinhao = new Catering_Rules.RawMaterial_Area().GetList("RawID=" + strRawID).Tables[0];
                    if (dt_pinhao != null && dt_pinhao.Rows.Count > 0)
                    {
                        this.Drop_Area.SelectedValue = dt_pinhao.Rows[0]["AreaID"].ToString();
                        this.txt_pinghao.Text = dt_pinhao.Rows[0]["InDBid"].ToString();
                    }
                    else
                    {
                        this.txt_pinghao.Text = "";
                    }

                    //显示营养元素值
                    DataTable dt_EN = new Catering_Rules.NutrientComposition().GetList(24, "RawID=" + strRawID, "NutritionElementsID").Tables[0];
                    if (dt_EN != null && dt_EN.Rows.Count > 0)
                    {
                        foreach (Control c in this.Pan_EN.Controls)
                        {
                            TextBox tb = c as TextBox;
                            if (tb != null)
                            {
                                int index = Convert.ToInt32(tb.ID.Replace("txt_", ""));
                                if (dt_EN.Rows.Count >= index)
                                {
                                    tb.Text = (dt_EN.Rows[index - 1]["Content"].ToString() == "" ? "0" : dt_EN.Rows[index - 1]["Content"].ToString());
                                }
                            }
                        }
                    }
                }
            }
        }

        //加载规格
        public void LoadUnit(int id)
        {
            this.LoadData();
            this.txt_U1.Text = string.Empty;
            this.txt_U2.Text = string.Empty;
            this.txt_U3.Text = string.Empty;
            this.txt_U4.Text = string.Empty;

            DataTable dt_RawMaterial_Unit = new Catering_Rules.RawMaterial_Unit().GetList("RawMaterialID=" + id.ToString() + " ORDER BY ID ").Tables[0];

            if (dt_RawMaterial_Unit != null && dt_RawMaterial_Unit.Rows.Count > 0)
            {
                for (int i = 0; i < dt_RawMaterial_Unit.Rows.Count; i++)
                {
                    string number = dt_RawMaterial_Unit.Rows[i]["Number"].ToString();
                    string tempid = dt_RawMaterial_Unit.Rows[i]["UnitID"].ToString();
                    if (i == 0)
                    {
                        this.txt_U1.Text = number;
                        this.Drop_U1.SelectedValue = tempid;
                    }
                    else if (i == 1)
                    {
                        this.txt_U2.Text = number;
                        this.Drop_U2.SelectedValue = tempid;
                    }
                    else if (i == 2)
                    {
                        this.txt_U3.Text = number;
                        this.Drop_U3.SelectedValue = tempid;
                    }
                    else if (i == 3)
                    {
                        this.txt_U4.Text = number;
                        this.Drop_U4.SelectedValue = tempid;
                    }
                }
            }

        }

        //变更区域
        protected void Drop_Area_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Request.QueryString["cid"] == null)
                return;

            string strRawID = Request.QueryString["cid"].ToString();
            string strAreaID = this.Drop_Area.SelectedValue;
            DataTable dt_pinhao = new Catering_Rules.RawMaterial_Area().GetList("RawID=" + strRawID + " and AreaID=" + strAreaID).Tables[0];
            if (dt_pinhao != null && dt_pinhao.Rows.Count > 0)
            {
                this.txt_pinghao.Text = dt_pinhao.Rows[0]["InDBid"].ToString();
            }
            else
            {
                this.txt_pinghao.Text = "";
            }
        }

        protected void LB_TongbuPinhao_Click(object sender, EventArgs e)
        {
            {
                string sql = "delete from RawMaterial_Area where id not in (select top 1 id from RawMaterial_Area as b where RawMaterial_Area.RawID=b.RawID and RawMaterial_Area.InDBid=b.InDBid order by b.ID DESC )";
                DbHelperSQL.ExecuteSql(sql);
                sql = "select distinct i.InDBid, i.RAWID from InDbInfo as i left join RawMaterial_Area ra on i.InDBid=ra.InDBid where i.RAWID<> ra.RawID";
                DataTable dt_indb0 = DbHelperSQL.Query(sql).Tables[0];
                if (dt_indb0 != null && dt_indb0.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_indb0.Rows.Count; i++)
                    {
                        string dbid = dt_indb0.Rows[i]["InDBid"].ToString();
                        int rawid = Convert.ToInt32(dt_indb0.Rows[i]["RawID"].ToString());
                        DataTable t0 = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + dbid + "'").Tables[0];
                        List<int> list = new List<int>();
                        if (t0 != null && t0.Rows.Count > 0)
                        {
                            for (int j = 0; j < t0.Rows.Count; j++)
                            {
                                int temprawid = Convert.ToInt32(t0.Rows[j]["RawID"].ToString());
                                list.Add(temprawid);
                            }
                            t0.Dispose();
                        }
                        if (list.Count > 0 && (!list.Contains(rawid)))
                        {
                            sql = " update InDbInfo set RawID=" + list[0] + " WHERE  InDBid='" + dbid + "'";
                            DbHelperSQL.ExecuteSql(sql);
                        }
                        else if (!list.Contains(rawid))
                        {
                            Catering_Model.RawMaterial_Area md_Raw_Area = new Catering_Model.RawMaterial_Area();
                            md_Raw_Area.id = new Catering_Rules.RawMaterial_Area().GetMaxId();
                            md_Raw_Area.RawID = rawid;
                            md_Raw_Area.AreaID = Convert.ToInt32(dbid.Substring(0, 1));
                            md_Raw_Area.InDBid = dbid;
                            new Catering_Rules.RawMaterial_Area().Add(md_Raw_Area);
                        }
                    }
                }

            }

            {
                string sql = "select distinct i.InDBid, i.RAWID from fromrecords as i left join RawMaterial_Area ra on i.InDBid=ra.InDBid where i.RAWID<> ra.RawID";
                DataTable dt_indb0 = DbHelperSQL.Query(sql).Tables[0];
                if (dt_indb0 != null && dt_indb0.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_indb0.Rows.Count; i++)
                    {
                        string dbid = dt_indb0.Rows[i]["InDBid"].ToString();
                        int rawid = Convert.ToInt32(dt_indb0.Rows[i]["RawID"].ToString());
                        DataTable t0 = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + dbid + "'").Tables[0];
                        List<int> list = new List<int>();
                        if (t0 != null && t0.Rows.Count > 0)
                        {
                            for (int j = 0; j < t0.Rows.Count; j++)
                            {
                                int temprawid = Convert.ToInt32(t0.Rows[j]["RawID"].ToString());
                                list.Add(temprawid);
                            }
                            t0.Dispose();
                        }
                        if (list.Count > 0 && (!list.Contains(rawid)))
                        {
                            sql = " update fromrecords set RawID=" + list[0] + " WHERE  InDBid='" + dbid + "'";
                            DbHelperSQL.ExecuteSql(sql);
                        }
                        //else
                        //{
                        //    Catering_Model.RawMaterial_Area md_Raw_Area = new Catering_Model.RawMaterial_Area();
                        //    md_Raw_Area.id = new Catering_Rules.RawMaterial_Area().GetMaxId();
                        //    md_Raw_Area.RawID = rawid;
                        //    md_Raw_Area.AreaID = Convert.ToInt32(dbid.Substring(0, 1));
                        //    md_Raw_Area.InDBid = dbid;
                        //    new Catering_Rules.RawMaterial_Area().Add(md_Raw_Area);
                        //}
                    }
                }

            }


            new Catering_Rules.RawMaterial_Area().DeleteListBywhere(" InDBid='' ");
            DataTable dt_pinhao = new Catering_Rules.RawMaterial_Area().GetErrorInDBIdList();
            Dictionary<int, string> Errorlist = new Dictionary<int, string>();//key:RawMaterial_Area的ID，value：RawMaterial_Area的InDBid
            if (dt_pinhao != null && dt_pinhao.Rows.Count > 0)
            {
                for (int i = 0; i < dt_pinhao.Rows.Count; i++)
                {
                    string indbid = dt_pinhao.Rows[i]["InDBid"].ToString();
                    DataTable dt_area = new Catering_Rules.RawMaterial_Area().GetList(" InDBid='" + indbid + "'").Tables[0];
                    if (dt_area != null && dt_area.Rows.Count > 0)
                    {
                        Dictionary<int, int> list = new Dictionary<int, int>();
                        for (int j = 0; j < dt_area.Rows.Count; j++)
                        {
                            int rawid = Convert.ToInt32(dt_area.Rows[j]["RawID"].ToString());
                            int id = Convert.ToInt32(dt_area.Rows[j]["ID"].ToString());
                            Catering_Model.E_RawMaterial md_Raw = new Catering_Rules.T_RawMaterial().GetModel(rawid);
                            if (md_Raw == null || md_Raw.id <= 0)
                            {
                                new Catering_Rules.RawMaterial_Area().Delete(id);
                            }
                            if (!(list.ContainsKey(id) && list[id] == rawid))
                            {
                                list.Add(id, rawid);
                            }
                        }
                        dt_area.Dispose();
                        if (list.Count == 1) return;
                        List<int> deleList = new List<int>();
                        List<int> saveList = new List<int>();

                        foreach (int aid in list.Keys)
                        {
                            int dt_count = new Catering_Rules.InDbInfo().GetList(" RAWID=" + list[aid] + " AND InDBid='" + indbid + "' ").Tables[0].Rows.Count;
                            if (dt_count == 0)
                            {
                                deleList.Add(aid);
                            }
                            else
                            {
                                saveList.Add(aid);
                            }
                        }

                        if (deleList.Count != list.Count)
                        {
                            foreach (int delid in deleList)
                            {
                                new Catering_Rules.RawMaterial_Area().Delete(delid);
                            }
                            if (saveList.Count > 1)
                            {
                                foreach (int saveid in saveList)
                                {
                                    Errorlist.Add(saveid, indbid);
                                }
                            }
                        }
                        else
                        {
                            for (int k = 0; k < deleList.Count - 1; k++)
                            {
                                new Catering_Rules.RawMaterial_Area().Delete(deleList[k]);
                            }
                        }
                    }
                }
                dt_pinhao.Dispose();
            }
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('同步成功！');</script>");
        }

        public bool IsAdmin()
        {
            if (Session["RoleID"] != null && !string.IsNullOrEmpty(Session["RoleID"].ToString()))
            {
                int role = 0;
                Int32.TryParse(Session["RoleID"].ToString(), out role);
                Catering_Model.Role model = new Catering_Rules.Role().GetModel(role);
                if (model != null && model.temp1 > 5) return true;
            }
            return false;
        }
    }
}